package com.simplegui.examples.pong;

import java.awt.Color;

import com.simplegui.api.Frame;
import com.simplegui.api.Game;
import com.simplegui.api.handlers.ButtonHandler;
import com.simplegui.api.handlers.DrawHandler;
import com.simplegui.api.handlers.KeyDownHandler;
import com.simplegui.api.handlers.KeyUpHandler;
import com.simplegui.api.util.Key;

public class Pong extends Game{

	private PongScore score;
	
	private Ball ball;
	
	private Paddle leftPaddle;
	private Paddle rightPaddle;
	
	private KeyDownHandler keyDownHandler;
	private KeyUpHandler keyUpHandler;
	private DrawHandler drawHandler;
	
	public Pong() {
		initComponents();
		initHandlers();
	}

	private void initComponents() {
		leftPaddle = new Paddle(this, Color.BLUE, 0, false);
		addGameComponent(leftPaddle);
		
		rightPaddle = new Paddle(this, Color.RED, PongConfigurations.FRAME_WIDTH, false);
		addGameComponent(rightPaddle);
		
		ball = new Ball(this);
		addGameComponent(ball);
		
		score = new PongScore();
	}

	private void initHandlers() {
		keyDownHandler = new KeyDownHandler() {
			@Override
			public void onKeyDown(Key key) {
			    if (Key.W == key){
			    	leftPaddle.decrementVelocity();
			    }else if (Key.S == key){
			    	leftPaddle.incrementVelocity();
			    }else if (Key.UP == key){
			    	rightPaddle.decrementVelocity();
			    }else if (Key.DOWN == key){
			    	rightPaddle.incrementVelocity();
			    }
			}		
		};
		
		keyUpHandler = new KeyUpHandler() {
			@Override
			public void onKeyUp(Key key) {
				if (Key.W == key){
					leftPaddle.incrementVelocity();       
				}else if (Key.S == key){
					leftPaddle.decrementVelocity();
				}else if (Key.UP == key){
					rightPaddle.incrementVelocity();
				}else if (Key.DOWN == key){
					rightPaddle.decrementVelocity();
				}
			}
		};
		
		drawHandler = new PongDrawHandler(this);

	}

	public void actionNewGame(){
		score.resetScore();
		ball.resetBall(false);
	}

	@Override
	public void configureFrame(Frame frame) {
		frame.setDrawHandler(drawHandler);
		frame.setKeyDownHandler(keyDownHandler);
		frame.setKeyUpHandler(keyUpHandler);
		
		frame.addButton("New Game", new ButtonHandler() {
			@Override
			public void onButtonPress() {
				actionNewGame();
			}
		});
	}

	public Paddle getLeftPaddle() {
		return leftPaddle;
	}
	
	public Paddle getRightPaddle() {
		return rightPaddle;
	}
	
	public Ball getBall() {
		return ball;
	}
	
	public PongScore getScore() {
		return score;
	}

}
